package ${modulePackage}.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class UrlUtils {

    /**
     * 拼接url
     *
     * @param url
     * @param parameters
     * @return
     */
    public static String getUrl(String url, String... parameters) {

        if (parameters.length == 0) {
            return url;
        }
        if (parameters.length % 2 != 0) {
            throw new RuntimeException("参数必须是2的倍数");
        }
        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append(url.contains("?") ? "&" : "?");
        urlBuilder.append(parameters[0]);
        urlBuilder.append("=");
        urlBuilder.append(encode(parameters[1]));
        for (int i = 2; i < parameters.length; i += 2) {
            urlBuilder.append("&");
            urlBuilder.append(parameters[i]);
            urlBuilder.append("=");
            urlBuilder.append(encode(parameters[i + 1]));
        }
        return urlBuilder.toString();
    }

    public static String encode(String s) {
        return encode(s, "utf-8");
    }

    public static String encode(String s, String encoding) {

        if (StringUtils.isBlank(s)) {
            return "";
        }
        if (StringUtils.isBlank(encoding)) {
            encoding = "utf-8";
        }
        try {
            return URLEncoder.encode(s, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    public static String decode(String s) {
        return decode(s, "utf-8");
    }

    public static String decode(String s, String encoding) {

        if (StringUtils.isBlank(s)) {
            return "";
        }
        if (StringUtils.isBlank(encoding)) {
            encoding = "utf-8";
        }
        try {
            return URLDecoder.decode(s, encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }
}
